﻿using System;
using System.IO;

namespace Gonte.Utilities
{
    public class DirectoryTraversal
    {
        public void Traverse(string path)
        {
            Traverse(new DirectoryInfo(path));
        }

        private void Traverse(DirectoryInfo directoryInfo)
        {
            ++level_;

            foreach (DirectoryInfo subDirectoryInfo in  directoryInfo.GetDirectories())
            {
                bool canTraverse = true;

                if (enterDirectory_ != null)
                {
                    canTraverse = enterDirectory_(subDirectoryInfo);
                }

                if (canTraverse)
                {
                    Traverse(subDirectoryInfo);
                }

                if (exitDirectory_ != null)
                {
                    exitDirectory_(subDirectoryInfo);
                }
            }

            --level_;
        }

        public delegate bool DirectoryHandler(DirectoryInfo directoryInfo);

        private DirectoryHandler enterDirectory_;
        private DirectoryHandler exitDirectory_;

        public DirectoryHandler EnterDirectory
        {
            get { return enterDirectory_; }
            set { enterDirectory_ = value; }
        }

        public DirectoryHandler ExitDirectory
        {
            get { return exitDirectory_; }
            set { exitDirectory_ = value; }
        }

        private int level_;

        public int Level
        {
            get { return level_; }
            set { level_ = value; }
        }
    }
}
